package com.gztms.job;

import com.gztms.blogmgnt.pojo.Blog;
import com.gztms.blogmgnt.service.BlogService;
import com.gztms.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Zoey
 * @date 2023/5/2 16:04
 * @Description TODO
 **/
@Component
public class UpdateViewCountJob {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private BlogService blogService;

    //测试时用这个  每5秒更新一次 0/5 * * * * ?

    /**
     * 每10分钟执行一次
     */
    @Scheduled(cron = "0 0/10 * * * ?")
    public void updateViewCount() {
        // 获取redis的viewCount
        Map<String, Object> cacheMap = redisCache.getCacheMap("blog:viewCount");
        // Map -> List
        List<Blog> blogs = cacheMap.entrySet()
                .stream()
                .map(entry -> new Blog(Integer.valueOf(entry.getKey()), (Integer) entry.getValue()))
                .collect(Collectors.toList());

        blogService.updateBatchById(blogs);
    }
}
